from machine import Pin, I2C
from sht30 import SHT30
import time
import network
import urequests

d5 = Pin(14, Pin.OUT)
d6 = Pin(12, Pin.OUT)
d7 = Pin(13, Pin.OUT)
d8 = Pin(2, Pin.OUT)

# i2c = I2C(-1, scl=Pin(2), sda=Pin(0), freq=400000)
# 扫描I2C总线数量
# i2c_address = i2c.scan()[0]
wlan = network.WLAN(network.STA_IF)
wlan.active(True)       # activate the interface

def connectwifi(name="m", password="88888888"):
    if not wlan.isconnected():
        print('connecting to network...')
        wlan.connect(name, password)
        while not wlan.isconnected():
            pass
    print('network config:', wlan.ifconfig())
    time.sleep(3)
#     main()

if __name__ == "__main__":
    connectwifi()
    sensor = SHT30()
    time.sleep(1)
#     temperature, humidity = sensor.measure()
#     print(float(str(temperature)))
#     print(float(str(humidity)))   
    while True:
#         try:
        temperature, humidity = sensor.measure()
#         except TypeError:
#             pass
        request = 'http://47.107.183.2/mushroom/update/?mbid=1&enfan=1&enhotfan=1&isgrow=1&humidifier=1&iswater=1&isqipe=1&enhum=1&encoldfan=0&hum=%s&temp=%s' % (str(humidity),str(temperature))
        response = urequests.get(request)
        print(response.text) 
        time.sleep(0.2)
        res = response.text
        print(int(res[2]))
        if int(res[1]) ==1:
            pass
        else:
            pass
         
        if int(res[2]) == 1:
            d5.off()
        else:
            d5.on()
            
        if int(res[3]) == 1:
            d6.off()
        else:
            d6.on()
            
        if int(res[4]) == 1:
            d7.off()
        else:
            d7.on()
            
        if int(res[5]) == 1:
            d8.off()
        else:
            d8.on()

        
         
         
    #sensor = SHT30()
#     while True:
#         print("measure start")
#         temperature, humidity = sensor.measure_init()
#         print("measure end")
#         print('Temperature:', ord(temperature), 'ºC, RH:', humidity, '%')